package org.anlu.jdk;

import org.anlu.model.Student;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * <p>
 *
 * @author anlu
 * @date 2024/1/9 9:15
 */
public class TGest {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {

//        testArray();

//        test1();

//        test2();

        test3();
    }


    public static void test1() throws ClassNotFoundException {
        //方式一(通过建立对象)
        Student stu = new Student();
        Class classobj1 = stu.getClass();
        System.out.println(classobj1.getName());

        //方式二（所在通过路径-相对路径）
        Class classobj2 = Class.forName("org.anlu.model.Student");
        System.out.println(classobj2.getName());

        //方式三（通过类名）
        Class classobj3 = Student.class;
        System.out.println(classobj3.getName());
    }

    public static void test2() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 下面这段代码是以反射机制的方式创建对象。
        // 通过反射机制，获取Class，通过Class来实例化对象
        Class c = Class.forName("org.anlu.model.Student");
        // newInstance() 这个方法会调用User这个类的无参数构造方法，完成对象的创建。
        // 重点是：newInstance()调用的是无参构造，必须保证无参构造是存在的！
        Object obj = c.newInstance();
        System.out.println(obj);

    }

    public static void test3() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class clazz1 = Class.forName("org.anlu.model.Student");

        //取得无参构造
        Constructor<?> constructor2 = clazz1.getConstructor();
//通过无参构造创建一个对象
        Object child1 = constructor2.newInstance();

//取得指定参数的构造方法对象
        Constructor<?> constructor3 = clazz1.getConstructor(int.class,String.class);
//通过构造方法对象创建一个对象
        constructor3.newInstance("wenpan",21);

    }


    public static void testArray() throws ClassNotFoundException {
        Class<?> cls = Class.forName("java.lang.String");
        Object array = Array.newInstance(cls, 25);
        //往数组里添加内容
        Array.set(array, 0, "Scala");
        Array.set(array, 1, "Java");
        Array.set(array, 2, "Groovy");
        Array.set(array, 3, "Scala");
        Array.set(array, 4, "Clojure");
        //获取某一项的内容
        System.out.println(Array.get(array, 3));
    }
}
